<?php
/**
 * Created by PhpStorm.
 * User: root
 * Date: 18-10-30
 * Time: 下午12:44
 */

namespace apps\httpd\libraries;


use apps\httpd\models\UeditorForm;
use mix\base\BaseObject;
use mix\facades\Log;
use mix\facades\Request;
use mix\facades\Session;
use mix\http\UploadFile;

class Ueditor extends BaseObject
{
    const FILE_READ_MODE = '0644';
    const FILE_WRITE_MODE = '0666';
    const DIR_READ_MODE = '0755';
    const  DIR_WRITE_MODE = '0777';

    //用于显示的图片路径
    public $pic_path;

    //url前缀
    public $UrlPrefix;
    public $url;

    //ueditor配置
    public $ueditor_config;
    public $ueditor_config_string = '{
    /* 上传图片配置项 */
    "imageActionName": "uploadimage", /* 执行上传图片的action名称 */
    "imageFieldName": "upfile", /* 提交的图片表单名称 */
    "imageMaxSize": 2048000, /* 上传大小限制，单位B */
    "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 上传图片格式显示 */
    "imageCompressEnable": true, /* 是否压缩图片,默认是true */
    "imageCompressBorder": 1600, /* 图片压缩最长边限制 */
    "imageInsertAlign": "none", /* 插入的图片浮动方式 */
    "imageUrlPrefix": "", /* 图片访问路径前缀 */
    "imagePathFormat": "/image/{yyyy}{mm}{dd}/", /* 上传保存路径,可以自定义保存路径 */
    							/* {uid} 会替换成当前用户id*/
                                /* {filename} 会替换成原文件名,配置这项需要注意中文乱码问题 */
                                /* {rand:6} 会替换成随机数,后面的数字是随机数的位数 */
                                /* {time} 会替换成时间戳 */
                                /* {yyyy} 会替换成四位年份 */
                                /* {yy} 会替换成两位年份 */
                                /* {mm} 会替换成两位月份 */
                                /* {dd} 会替换成两位日期 */
                                /* {hh} 会替换成两位小时 */
                                /* {ii} 会替换成两位分钟 */
                                /* {ss} 会替换成两位秒 */
                                /* 非法字符 \ : * ? " < > | */

    /* 涂鸦图片上传配置项 */
    "scrawlActionName": "uploadscrawl", /* 执行上传涂鸦的action名称 */
    "scrawlFieldName": "upfile", /* 提交的图片表单名称 */
    "scrawlPathFormat": "/image/{yyyy}{mm}{dd}/", /* 上传保存路径,可以自定义保存路径 */
    "scrawlMaxSize": 2048000, /* 上传大小限制，单位B */
    "scrawlUrlPrefix": "", /* 图片访问路径前缀 */
    "scrawlInsertAlign": "none",

    /* 截图工具上传 */
    "snapscreenActionName": "uploadimage", /* 执行上传截图的action名称 */
    "snapscreenPathFormat": "/image/{yyyy}{mm}{dd}/", /* 上传保存路径,可以自定义保存路径 */
    "snapscreenUrlPrefix": "", /* 图片访问路径前缀 */
    "snapscreenInsertAlign": "none", /* 插入的图片浮动方式 */

    /* 抓取远程图片配置 */
    "catcherLocalDomain": ["127.0.0.1", "localhost", "img.baidu.com"],
    "catcherActionName": "catchimage", /* 执行抓取远程图片的action名称 */
    "catcherFieldName": "source", /* 提交的图片列表表单名称 */
    "catcherPathFormat": "/image/{yyyy}{mm}{dd}/", /* 上传保存路径,可以自定义保存路径 */
    "catcherUrlPrefix": "", /* 图片访问路径前缀 */
    "catcherMaxSize": 2048000, /* 上传大小限制，单位B */
    "catcherAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 抓取图片格式显示 */

    /* 上传视频配置 */
    "videoActionName": "uploadvideo", /* 执行上传视频的action名称 */
    "videoFieldName": "upfile", /* 提交的视频表单名称 */
    "videoPathFormat": "/video/{yyyy}{mm}{dd}/", /* 上传保存路径,可以自定义保存路径 */
    "videoUrlPrefix": "", /* 视频访问路径前缀 */
    "videoMaxSize": 102400000, /* 上传大小限制，单位B，默认100MB */
    "videoAllowFiles": [
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"], /* 上传视频格式显示 */

    /* 上传文件配置 */
    "fileActionName": "uploadfile", /* controller里,执行上传视频的action名称 */
    "fileFieldName": "upfile", /* 提交的文件表单名称 */
    "filePathFormat": "/file/{yyyy}{mm}{dd}/", /* 上传保存路径,可以自定义保存路径 */
    "fileUrlPrefix": "", /* 文件访问路径前缀 */
    "fileMaxSize": 20480000, /* 上传大小限制，单位B，默认20MB */
    "fileAllowFiles": [
        ".png", ".jpg", ".jpeg", ".gif", ".bmp",
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
    ], /* 上传文件格式显示 */

    /* 列出指定目录下的图片 */
    "imageManagerActionName": "listimage", /* 执行图片管理的action名称 */
    "imageManagerListPath": "/image/", /* 指定要列出图片的目录 */
    "imageManagerListSize": 20, /* 每次列出文件数量 */
    "imageManagerUrlPrefix": "", /* 图片访问路径前缀 */
    "imageManagerInsertAlign": "none", /* 插入的图片浮动方式 */
    "imageManagerAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 列出的文件类型 */

    /* 列出指定目录下的文件 */
    "fileManagerActionName": "listfile", /* 执行文件管理的action名称 */
    "fileManagerListPath": "/file/", /* 指定要列出文件的目录 */
    "fileManagerUrlPrefix": "", /* 文件访问路径前缀 */
    "fileManagerListSize": 20, /* 每次列出文件数量 */
    "fileManagerAllowFiles": [
        ".png", ".jpg", ".jpeg", ".gif", ".bmp",
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
    ] /* 列出的文件类型 */

}';

    //上传目录
    public $upload_path;

    //要输出的数据
    public $output_data;

    //回调参数
    public $callback;

    public function onConstruct()
    {
        parent::onConstruct(); // TODO: Change the autogenerated stub
        $this->ueditor_config = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", $this->ueditor_config_string), true);
        $this->UrlPrefix= "http://ueditor.luoanman.com/uploads/";
        $this->url="http://ueditor.luoanman.com";
        $this->upload_path = app()->getPublicPath() . '/uploads/';
        $this->pic_path = '/uploads/';

        //上传动作
        $action = Request::get('action');
        switch ($action) {

            case 'config':
                $result = json_encode($this->ueditor_config);
                break;

            case 'uploadimage':
                $config = array(
                    "pathFormat" => $this->ueditor_config['imagePathFormat'],
                    "max_size" => $this->ueditor_config['imageMaxSize'],
                );
                $fieldName = $this->ueditor_config['imageFieldName'];
                $result = $this->uploadFile($config, $fieldName);
                break;

            case 'uploadscrawl':
                $config = array(
                    "pathFormat" => $this->ueditor_config['scrawlPathFormat'],
                    "maxSize" => $this->ueditor_config['scrawlMaxSize'],
                    "oriName" => "scrawl.png"
                );
                $fieldName = $this->ueditor_config['scrawlFieldName'];
                $result = $this->uploadBase64($config, $fieldName);
                break;

            case 'uploadvideo':
                $config = array(
                    "pathFormat" => $this->ueditor_config['videoPathFormat'],
                    "max_size" => $this->ueditor_config['videoMaxSize'],
                );
                $fieldName = $this->ueditor_config['videoFieldName'];
                $result = $this->uploadFile($config, $fieldName);
                break;

            case 'uploadfile':
                // default:
                $config = array(
                    "pathFormat" => $this->ueditor_config['filePathFormat'],
                    "max_size" => $this->ueditor_config['fileMaxSize'],
                );

                $fieldName = $this->ueditor_config['fileFieldName'];
                $result = $this->uploadFile($config, $fieldName);
                break;

            case 'listfile':
                $config = array(
                    'allowFiles' => $this->ueditor_config['fileManagerAllowFiles'],
                    'listSize' => $this->ueditor_config['fileManagerListSize'],
                    'path' => $this->ueditor_config['fileManagerListPath'],
                );
                $result = $this->listFile($config);
                break;

            case 'listimage':
                $config = array(
                    'allowFiles' => $this->ueditor_config['imageManagerAllowFiles'],
                    'listSize' => $this->ueditor_config['imageManagerListSize'],
                    'path' => $this->ueditor_config['imageManagerListPath']
                );
                $result = $this->listFile($config);
                break;

            case 'catchimage':
                $config = array(
                    "pathFormat" => $this->ueditor_config['catcherPathFormat'],
                    "maxSize" => $this->ueditor_config['catcherMaxSize'],
                    "oriName" => "remote.png"
                );
                $fieldName = $this->ueditor_config['catcherFieldName'];
                $result = $this->saveRemote($config, $fieldName);
                break;

            default:
                $result = json_encode(array('state' => '请求错误'));
                break;

        }

        //返回值
        $this->callback = Request::get('callback');

        if ($this->callback) {
            if (preg_match("/^[\w_]+$/", $this->callback)) {
                $this->output_data = htmlspecialchars($this->callback) . '(' . $result . ')';
            } else {
                $this->output_data = json_encode(array(
                    'state' => 'callback参数不合法'
                ));
            }
        } else {
            $this->output_data = $result;
        }
    }


    /**
     * 上传文件方法
     *
     */



    private function uploadFile($config, $fieldName)
    {

        //文件路径（ueditor配置中）
        $file_name = ltrim(self::_get_full_path($config['pathFormat']), '/');
        $max_size = $config['max_size'];// 设置附件上传大小


        //创建目录
        self::create_dir($this->upload_path . $file_name);

        $model_ueditor = new UeditorForm($max_size, $fieldName);
        $model_ueditor->attributes = Request::post() + Request::get();
        $model_ueditor->setScenario('upfile');
        if (!$model_ueditor->validate()) {
            $data = ['state' => $model_ueditor->getErrors()];
        }
        $file = UploadFile::newInstanceByName($fieldName);
        $file_path = $this->upload_path . $file_name . $file->getBaseName() .'.'.$file->getExtension();
        $file->saveAs($file_path);

        $data = array(
            'state' => "SUCCESS",
            'url' => $this->url.$this->pic_path . $file_name . $file->getBaseName() . '.'.$file->getExtension(),
            'title' => $file->getBaseName(),
            'original' => $file->getBaseName(),
            'file_ext' => $file->getExtension(),
            'size' => $file->size,
        );

        return json_encode($data);
    }


    /**
     * 列出文件夹下所有文件，如果是目录则向下
     */
    private function listFile($config)
    {

        $allowFiles = substr(str_replace(".", "|", join("", $config['allowFiles'])), 1);

        $size = Request::get('size') ? Request::get('size') : $config['listSize'];
        $start = Request::get('start') ? Request::get('start') : 0;
        $end = $start + $size;

        $path = $this->upload_path . $config['path'];

        $files = self::getfiles($path, $allowFiles);
        //return $files;
        if(!is_array($files)){
            return json_encode(array(
                "state" => "没有匹配的文件",
                "list" => array(),
                "start" => $start,
                "total" => 0,
            ));
        }
        if (!count($files)) {
            return json_encode(array(
                "state" => "没有匹配的文件",
                "list" => array(),
                "start" => $start,
                "total" => 0,
            ));
        }

        /* 获取指定范围的列表 */
        $len = count($files);
        for ($i = min($end, $len) - 1, $list = array(); $i < $len && $i >= 0 && $i >= $start; $i--) {
            $list[] = $files[$i];
        }

        /* 返回数据 */
        $result = json_encode(array(
            "state" => "SUCCESS",
            "list" => $list,
            "start" => $start,
            "total" => count($files)
        ));

        return $result;
    }


    /**
     *
     * 获取远程图片
     */
    private function saveRemote($config, $fieldName)
    {
        $list = array();

        //获得资源名称
        $source = Request::post($fieldName) + Request::get($fieldName);

        if (!$source) {
            return json_encode(array(
                'state' => '图片不能为空'
            ));
        }

        foreach ($source as $imgUrl) {

            $imgUrl = htmlspecialchars($imgUrl);
            $imgUrl = str_replace("&amp;", "&", $imgUrl);

            //http开头验证
            if (strpos($imgUrl, "http") !== 0) {
                $data = array('state' => '不是http链接');
                return json_encode($data);
            }

            $heads = get_headers($imgUrl);
            //格式验证(扩展名验证和Content-Type验证)
            $fileType = strtolower(strrchr($imgUrl, '.'));
            if (!in_array($fileType, $config['allowFiles']) || stristr($heads['Content-Type'], "image")) {
                $data = array("state" => "错误文件格式");
                return json_encode($data);
            }

            //打开输出缓冲区并获取远程图片
            ob_start();
            $context = stream_context_create(
                array('http' => array(
                    'follow_location' => false // don't follow redirects
                ))
            );
            readfile($imgUrl, false, $context);
            $img = ob_get_contents();
            ob_end_clean();
            preg_match("/[\/]([^\/]*)[\.]?[^\.\/]*$/", $imgUrl, $m);

            $path = $this->getFullPath($config['pathFormat']);
            if (strlen($img) > $config['maxSize']) {
                $data['states'] = '文件太大';
                return json_encode($data);
            }

            $imgname = self::_get_rand_file_name() . '.png';
            $oriName = $m ? $m[1] : "";

            $flile_name = ltrim(self::_get_full_path($config['pathFormat']), '/');

            //返回的图片路径
            $pic_path = $this->pic_path . $flile_name . $imgname;

            //上传路径
            $upload_path = $this->upload_path . $flile_name;

            //创建目录
            self::create_dir($upload_path);

            if (file_put_contents($this->upload_path . $flile_name . $imgname, $img)) {
                array_push($list, array(
                    "state" => 'SUCCESS',
                    "url" => $this->url.$pic_path,
                    "size" => strlen($img),
                    "title" => $imgname,
                    "original" => $oriName,
                    "source" => htmlspecialchars($imgUrl)
                ));
            } else {
                array_push($list, array('state' => '文件写入失败'));
            }
        }

        /* 返回抓取数据 */
        return json_encode(array(
            'state' => count($list) ? 'SUCCESS' : 'ERROR',
            'list' => $list
        ));
    }


    /**
     *
     *解析base64编码(涂鸦)
     */
    private function uploadBase64($config, $fieldName)
    {
        $data = array();

        $base64Data = Request::post($fieldName);

        $img = base64_decode($base64Data);

        if (strlen($img) > $config['maxSize']) {
            $data['states'] = '文件太大';
            return json_encode($data);
        }

        //替换随机字符串
        $imgname = self::_get_rand_file_name() . '.png';

        $flile_name = ltrim(self::_get_full_path($config['pathFormat']), '/');

        //返回的图片路径
        $pic_path = $this->url.$this->pic_path . $flile_name . $imgname;

        //上传路径
        $upload_path = $this->upload_path . $flile_name;
        //创建目录
        self::create_dir($upload_path);

        if (file_put_contents($this->upload_path . $flile_name . $imgname, $img)) {

            $data = array(
                'state' => 'SUCCESS',
                'url' => $pic_path,
                'title' => $imgname,
                'original' => 'scrawl.png',
                'type' => '.png',
                'size' => strlen($img),

            );
        } else {
            $data = array(
                'state' => '文件夹不可写',
            );
        }
        return json_encode($data);
    }


    /**
     * 输出结果
     * @param data 数组数据
     * @return 组合后json格式的结果
     */
    public function output_data()
    {

        return $this->output_data;
    }


    /**
     * 规则替换命名文件
     * @param $path
     * @return string
     */
    static private function _get_full_path($path)
    {
        //替换日期事件
        $t = time();
        $d = explode('-', date("Y-y-m-d-H-i-s"));
        $format = $path;
        $format = str_replace("{yyyy}", $d[0], $format);
        $format = str_replace("{yy}", $d[1], $format);
        $format = str_replace("{mm}", $d[2], $format);
        $format = str_replace("{dd}", $d[3], $format);
        $format = str_replace("{hh}", $d[4], $format);
        $format = str_replace("{ii}", $d[5], $format);
        $format = str_replace("{ss}", $d[6], $format);
        $format = str_replace("{time}", $t, $format);

        return $format;
    }


    /**
     * 获得被允许的文件类型
     * @param unknown $AllowFiles
     * @return string
     */
    static private function _get_allow_files($AllowFiles)
    {
        $data = '';
        foreach ($AllowFiles as $key => $value) {
            $data .= ltrim($value, '.') . '|';
        }
        return trim($data, '|');
    }

    /**
     * 创建目录
     * @param unknown $path
     */
    static private function create_dir($path)
    {
        if (!is_dir($path)) {
            return mkdir($path, self::DIR_WRITE_MODE, true);
        }
    }


    /**
     * 获得随机文件名
     */
    private function _get_rand_file_name()
    {
        return md5(uniqid());
    }


    /**
     * 遍历获取目录下的指定类型的文件
     * @param $path
     * @param array $files
     * @return array
     */
    public function getfiles($path, $allowFiles = 'all', &$files = array())
    {

        if (!is_dir($path)) return null;
        if (substr($path, strlen($path) - 1) != '/') $path .= '/';
        $handle = opendir($path);
        while (false !== ($file = readdir($handle))) {
            if ($file != '.' && $file != '..') {
                $path2 = $path . $file;
                if (is_dir($path2)) {
                    $this->getfiles($path2, $allowFiles, $files);
                } else {
                    if ($allowFiles != 'all') {
                        if (preg_match("/\.(" . $allowFiles . ")$/i", $file)) {
                            $files[] = array(
                                'url' => $this->UrlPrefix.substr($path2, strlen($this->upload_path)),
                                'mtime' => filemtime($path2)
                            );
                        }
                    } else {
                        $files[] = array(
                            'url' => $this->UrlPrefix.substr($path2, strlen($this->upload_path)),
                            'mtime' => filemtime($path2)
                        );
                    }
                }
            }
        }
        return $files;
    }

}
